<template>
  <el-card class="submit-form">
    <div class="submit-content">
      <!-- 表单部分 -->
      <div class="form-section">
        <el-form :model="form" :rules="rules" ref="submitForm" label-width="80px">
          <el-form-item label="上传者" prop="uploader">
            <el-input v-model="form.uploader" placeholder="请输入您的名称"></el-input>
          </el-form-item>

          <el-form-item label="经度" prop="longitude">
            <el-input v-model="form.longitude" placeholder="例如: 116.404">
              <template #append>
                <el-button @click="pickCoordinates" icon="Position" title="从地图拾取坐标"></el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="纬度" prop="latitude">
            <el-input v-model="form.latitude" placeholder="例如: 39.915">
              <template #append>
                <el-button @click="pickCoordinates" icon="Position" title="从地图拾取坐标"></el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="备注">
            <el-input
                v-model="form.remarks"
                type="textarea"
                :rows="2"
                placeholder="可选填写"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                @click="submitForm"
                :loading="submitting"
                style="width: 100%">
              {{ submitting ? '上传中...' : '提交数据' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 上传区域 -->
      <div class="upload-section">
        <div
            class="upload-area"
            @dragover.prevent="dragOver = true"
            @dragleave="dragOver = false"
            @drop.prevent="handleDrop"
            :class="{ 'drag-over': dragOver }"
            @click="triggerFileInput"
        >
          <div v-if="!previewImage" class="upload-prompt">
            <el-icon :size="40"><Upload /></el-icon>
            <p>拖拽图片到此处</p>
            <p class="hint">支持 JPG/PNG 格式，最大 5MB</p>
          </div>
          <div v-else class="image-preview">
            <img :src="previewImage" alt="Preview" style="width: 100%; height: 100%; object-fit: contain;">
            <div class="image-actions">
              <el-button circle @click.stop="removeImage">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <input
              type="file"
              ref="fileInput"
              @change="handleFileSelect"
              accept="image/jpeg,image/png"
              style="display: none"
          >
        </div>
      </div>
    </div>
  </el-card>
</template>

<script>
import { ElMessage } from 'element-plus'
import { Upload, Delete, Position } from '@element-plus/icons-vue'
import auth from '../api/auth'

export default {
  name: 'SubmitForm',
  components: {
    Upload,
    Delete,
    Position
  },
  props: {
    coordinates: {
      type: Object,
      default: () => ({ longitude: '', latitude: '' })
    }
  },
  data() {
    return {
      dragOver: false,
      previewImage: null,
      file: null,
      submitting: false,
      form: {
        uploader: '',
        longitude: '',
        latitude: '',
        remarks: ''
      },
      rules: {
        uploader: [
          { required: true, message: '请输入上传者名称', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请输入经度', trigger: 'blur' },
          { pattern: /^-?\d{1,3}(\.\d+)?$/, message: '请输入有效的经度值', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '请输入纬度', trigger: 'blur' },
          { pattern: /^-?\d{1,2}(\.\d+)?$/, message: '请输入有效的纬度值', trigger: 'blur' }
        ]
      },
      pickingCoordinates: false
    }
  },
  watch: {
    coordinates: {
      immediate: true,
      handler(newVal) {
        this.form.longitude = newVal.longitude
        this.form.latitude = newVal.latitude
      }
    }
  },
  methods: {
    pickCoordinates() {
      this.pickingCoordinates = true
      ElMessage.info('请在地图上点击选择位置')
      this.$emit('start-pick-coordinates')
    },
    handlePickedCoordinates(lng, lat) {
      this.form.longitude = lng
      this.form.latitude = lat
      this.pickingCoordinates = false
    },
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    handleFileSelect(e) {
      const files = e.target.files
      if (files && files.length > 0) {
        this.processFile(files[0])
      }
    },
    handleDrop(e) {
      this.dragOver = false
      const files = e.dataTransfer.files
      if (files && files.length > 0) {
        this.processFile(files[0])
      }
    },
    handlePaste(e) {
      const items = e.clipboardData.items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          const blob = items[i].getAsFile()
          this.processFile(blob)
          break
        }
      }
    },
    updateCoordinates(lng, lat) {
      this.form.longitude = lng
      this.form.latitude = lat
    },
    processFile(file) {
      const validTypes = ['image/jpeg', 'image/png']
      const maxSize = 5 * 1024 * 1024

      if (!validTypes.includes(file.type)) {
        ElMessage.error('只支持 JPG/PNG 格式图片')
        return
      }

      if (file.size > maxSize) {
        ElMessage.error('图片大小不能超过 5MB')
        return
      }

      this.file = file

      const reader = new FileReader()
      reader.onload = (e) => {
        this.previewImage = e.target.result
      }
      reader.readAsDataURL(file)
    },
    removeImage() {
      this.previewImage = null
      this.file = null
      this.$refs.fileInput.value = ''
    },
    submitForm() {
      this.$refs.submitForm.validate((valid) => {
        if (valid) {
          if (!this.file) {
            ElMessage.warning('请上传图片');
            return;
          }

          this.submitting = true;

          // 查找匹配的 Point
          const minX = parseFloat(this.form.longitude) - 0.003;
          const minY = parseFloat(this.form.latitude) - 0.003;
          const maxX = parseFloat(this.form.longitude) + 0.003;
          const maxY = parseFloat(this.form.latitude) + 0.003;

          auth.getPoints(minX, minY, maxX, maxY).then(response => {
            const result = response.data;
            let pid = null;

            if (result.code === '200' && result.data.length > 0) {
              // 找到最近的 Point
              const nearestPoint = result.data.reduce((closest, point) => {
                const dist = Math.sqrt(
                    Math.pow(parseFloat(point.longitude) - parseFloat(this.form.longitude), 2) +
                    Math.pow(parseFloat(point.latitude) - parseFloat(this.form.latitude), 2)
                );
                return dist < closest.distance ? { point, distance: dist } : closest;
              }, { point: null, distance: Infinity }).point;
              pid = nearestPoint.pid;
            }

            if (!pid) {
              // 生成新的 pid
              pid =  Math.random().toString(36).substr(2, 9);
              // 创建新的 Point
              auth.addPoint({
                pid: pid,
                longitude: this.form.longitude,
                latitude: this.form.latitude,
                name: this.form.remarks || '',
                username: this.form.uploader
              }).then(() => {
                this.uploadImage(pid);
              }).catch(error => {
                ElMessage.error(`创建 Point 失败: ${error.response?.data?.message || error.message}`);
                this.submitting = false;
              });
            } else {
              this.uploadImage(pid);
            }
          }).catch(error => {
            ElMessage.error(`查找 Point 失败: ${error.response?.data?.message || error.message}`);
            this.submitting = false;
          });
        }
      });
    },
    uploadImage(pid) {
      auth.uploadImage(this.file, pid).then(response => {
        if (response.data && response.data.code === '0') {
          ElMessage.success('提交成功！');
          this.resetForm();
        } else {
          ElMessage.error(response.data?.message || '提交失败');
        }
      }).catch(error => {
        const errorMsg = error.response?.data?.message || error.message;
        ElMessage.error(`上传图片失败: ${errorMsg}`);
      }).finally(() => {
        this.submitting = false;
      });
    },
    resetForm() {
      this.$refs.submitForm.resetFields()
      this.removeImage()
    }
  },
  mounted() {
    document.addEventListener('paste', this.handlePaste)
    this.$emit('form-mounted', this.handlePickedCoordinates)
  },
  beforeUnmount() {
    document.removeEventListener('paste', this.handlePaste)
  }
}
</script>

<style scoped>
.submit-form {
  height: 100%;
  padding: 5px;
  overflow-y: auto;
}

.submit-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100%;
}

.form-section {
  flex: 1;
}

.upload-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.upload-area {
  flex: 1;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #f5f7fa;
  position: relative;
  overflow: hidden;
  min-height: 150px;
}

.upload-area:hover {
  border-color: #409eff;
}

.drag-over {
  border-color: #409eff !important;
  background-color: #ecf5ff;
}

.upload-prompt {
  text-align: center;
  color: #909399;
  padding: 15px;
}

.upload-prompt .hint {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 8px;
}

.image-preview {
  width: 100%;
  height: 100%;
  position: relative;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.image-actions {
  position: absolute;
  bottom: 8px;
  right: 8px;
}

:deep(.el-form-item__label) {
  font-size: 14px;
}

:deep(.el-input__inner) {
  font-size: 14px;
}

:deep(.el-textarea__inner) {
  font-size: 14px;
}
</style>
